﻿using System;
using Shuba.Model;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using System.Configuration;
using DynamicComparer;

namespace Shuba.Web.audit
{
    public partial class audit_trail : basePage
    {
        int rowsPerPage;
        string currentPage;
        int jmlRow;

        protected void Page_Load(object sender, EventArgs e)
        {
            rowsPerPage = 20;

            if (!IsPostBack)
            {
                string acl = GetUserAccess("AUDIT_TRAIL");

                if (!IsUserView(acl))
                {
                    string msg = this.GetGlobalResourceObject("Messages", "NoPrivilege").ToString();
                    AlertAndRedirect(msg, ResolveUrl(ConfigurationManager.AppSettings["default_url"]));
                }

                LabelTitle.Text = GetPageTitle("AUDIT_TRAIL");

                Shuba.Business.AuditTrail log = new Shuba.Business.AuditTrail();
                List<AuditTrailInfo> TableList = log.GetTableList();
                ddlTable.DataSource = TableList;
                ddlTable.DataValueField = "TABLE_NAME";
                ddlTable.DataTextField = "TABLE_NAME";
                ddlTable.DataBind();

                txtStartDate.Text = ProcessingDate().ToString("dd MMMM yyyy");
                txtToDate.Text = ProcessingDate().ToString("dd MMMM yyyy");

                InitSort();
                ViewState["searchBy"] = "";
                currentPage = "1";
                ViewState["SortEx"] = "UPDATE_DATE";
                ViewState["Sort"] = "DESC";

                BindData();
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            if (Convert.ToDateTime(txtToDate.Text) >= Convert.ToDateTime(txtStartDate.Text))
            {
                BindData();
            }
            else
            {
                string msg = this.GetGlobalResourceObject("Messages", "InvalidDateRange").ToString();
                Alert(msg);
            }
        }

        public void InitSort()
        {
            ViewState.Add("Sort", "DESC");
            ViewState.Add("SortEx", "");
        }

        private void BindData()
        {
            DateTime startDate, endDate;
            Shuba.Business.AuditTrail log = new Shuba.Business.AuditTrail();

            if (txtStartDate.Text != "")
            {
                startDate = Convert.ToDateTime(txtStartDate.Text);
            }
            else
            {
                startDate = ProcessingDate();
            }

            if (txtToDate.Text != "")
            {
                endDate = Convert.ToDateTime(txtToDate.Text);
            }
            else
            {
                endDate = ProcessingDate();
            }

            List<AuditTrailInfo> list;

            if (ddlPage.Items.Count == 0)
                currentPage = "1";
            else currentPage = ddlPage.SelectedValue;

            jmlRow = log.GetRowNumber(ddlTable.SelectedValue.Trim(), startDate, endDate);

            list = log.GetList(ddlTable.SelectedValue.Trim(), startDate, endDate, int.Parse(currentPage), gvList.PageSize);
            ViewState["List"] = list;

            gvList.DataSource = list;
            gvList.DataBind();
            load_data_topup_page();
        }

        protected void load_data_topup_page()
        {
            int jmlHal = (int)Math.Ceiling((decimal)jmlRow / (decimal)rowsPerPage);
            string pageNum;

            footLink.Visible = (jmlHal > 0);

            ddlPage.Items.Clear();
            for (int i = 0; i < jmlHal; i++)
            {
                pageNum = (i + 1).ToString();
                ddlPage.Items.Add(new ListItem(pageNum, pageNum));
            }

            if (ViewState["searchBy"].ToString() == ddlTable.SelectedValue)
                ddlPage.SelectedValue = currentPage;
            ViewState["searchBy"] = ddlTable.SelectedValue;

            lblPage.Text = "Page " + currentPage + " of " + jmlHal;

            firstLink.Visible = true;
            prevLink.Visible = true;
            nextLink.Visible = true;
            lastLink.Visible = true;

            if (ddlPage.SelectedIndex <= 0)
            {
                firstLink.Visible = false;
                prevLink.Visible = false;
            }
            if (ddlPage.SelectedIndex >= ddlPage.Items.Count - 1)
            {
                nextLink.Visible = false;
                lastLink.Visible = false;
            }
        }

        protected void btnExcel_Click(object sender, EventArgs e)
        {
            gvList.AllowPaging = false;
            BindData();
            GridViewExportUtil.Export("audit_" + ConfigurationManager.AppSettings["app.code"] + "_" + ProcessingDate().ToString("ddMMMyyyy") + ".xls", gvList);
        }

        protected void gvList_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvList.PageIndex = e.NewPageIndex;
            BindData();
        }

        protected void gvList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                switch (e.Row.Cells[0].Text.ToUpper())
                {
                    case "I":
                        e.Row.Cells[0].Text = "INSERT";
                        break;
                    case "U":
                        e.Row.Cells[0].Text = "UPDATE";
                        break;
                    case "D":
                        e.Row.Cells[0].Text = "DELETE";
                        break;
                }
            }
        }

        protected void gvList_Sorting(object sender, GridViewSortEventArgs e)
        {
            SortDirection(e.SortExpression, e.SortDirection.ToString());
            ViewState["SortEx"] = e.SortExpression;
            gvList.PageIndex = 0;

            if (ViewState["SortEx"].ToString().Trim() != "")
            {
                List<AuditTrailInfo> list = (List<AuditTrailInfo>)ViewState["List"];

                string sort = sort = ViewState["SortEx"].ToString() + " " + ViewState["Sort"];
                DynamicComparer<AuditTrailInfo> comparer = new DynamicComparer<AuditTrailInfo>(sort);
                list.Sort(comparer);

                gvList.DataSource = list;
                gvList.DataBind();
            }
        }

        protected void ddlPipelinePage_IndexChange(object sender, EventArgs e)
        {
            BindData();
        }

        protected void linkDataPage_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            if (sender == firstLink) ddlPage.SelectedIndex = 0;
            else if (sender == prevLink) ddlPage.SelectedIndex--;
            else if (sender == nextLink) ddlPage.SelectedIndex++;
            else if (sender == lastLink) ddlPage.SelectedIndex = ddlPage.Items.Count - 1;
            BindData();
        }
    }
}